
const fs = require('fs')
const request = require('request')
const wecomServer = require('../server/wecom')
module.exports = async function (app, models, $, db, nm) {
    let wecom = wecomServer(app, models, $, db, nm)
    //商城相关接口
    var tencent = new $.Tencent(Config.tencent);
    //会员登录
    function wxmemberLogin(req,res,wxmember) {
        var wxmemberInfo = wxmember;
        nm.setSessionRouter(req,res,{
            // id: wxmember.session_key,
            session_key:wxmember.session_key,
            unitId: wxmember.unitId,
            userId: wxmember.userId,
            memberId:wxmember.id,
            userName: wxmember.openId,
            platform: 'WeChatMiniApp',
            enterpriceId:wxmember.enterpriceId,
            enterpriceName:wxmember.enterpriceName,
            type: 2
        }, ret => {
            if (!ret.errorMsg) {
                models.user.find({id:wxmember.userId},user => {
                    wxmemberInfo.token = ret.id;
                    wxmemberInfo.userName = user.userName
                    wxmemberInfo.name = user.name
                    wxmemberInfo.photo = user.photo
                    wxmemberInfo.enterpriceId = user.enterpriceId
                    wxmemberInfo.enterpriceName = user.enterpriceName
                    res.send(wxmemberInfo);
                },{
                    join:{
                        enterpriceId:{
                            name:'unit',
                            type:'LEFT',
                            key:'unitId',
                            projection:{
                                name:'unitName'
                            }
                        }
                    }
                })
            } else if(/Duplicate entry/.test(ret.errorMsg)){
                models.session.find({id:wxmember.session_key},function(ret){
                    if(ret.id) wxmemberInfo.token = ret.id;
                    res.send(ret.errorMsg ? ret : wxmemberInfo);
                })
            }else{
                res.send(ret);
            }
        })
    }
    /**
     * 获取企业打卡记录
     * unitId 必填 单位id
     * opencheckindatatype 打卡类型。1：上下班打卡；2：外出打卡；3：全部打卡(默认)
     * starttime 必填 开始时间 Unix时间戳
     * endtime 必填 结束时间 Unix时间戳
     * **/
    app.post('/v2/wecom/getcheckindata',async (req,res) => {
        res.send(await wecom.getcheckindata(req.body))
    })
    /**
     * 获取企业打卡日报数据
     * unitId 必填 单位id
     * starttime 必填 开始时间 Unix时间戳
     * endtime 必填 结束时间 Unix时间戳
     * **/
     app.post('/v2/wecom/getcheckinDaydata',async (req,res) => {
        res.send(await wecom.getcheckinDaydata(req.body))
    })
    /**
     * 获取企业打卡月报数据
     * unitId 必填 单位id
     * starttime 必填 开始时间 Unix时间戳
     * endtime 必填 结束时间 Unix时间戳
     * **/
     app.post('/v2/wecom/getcheckinMonthdata',async (req,res) => {
        res.send(await wecom.getcheckinMonthdata(req.body))
    })
    //code换取openId
    app.get('/WeChatMiniAppLogin', function (req, res) {
        if (req.query.code) {
            tencent.auth.code2Session(req.query.code,async function (ret) {
                console.log('code2session',ret);
                
                if (!ret.errorMsg) {
                    let wxmemberRet = await models.member.findSync({ openId: ret.openid },{
                        join:{
                            userId:{
                                type: 'LEFT',
                                name: 'user',
                                key: 'id',//默认
                                projection: {
                                    name: 1
                                }
                            }
                        }
                    })
                    if (!wxmemberRet.id) {
                        wxmemberRet = await models.member.insertSync({
                            openId: ret.openid,
                            unitId: req.query.unitId
                        })
                        if (!wxmemberRet.errorMsg) {
                            wxmemberRet.openId = ret.openid;
                            wxmemberRet.session_key = ret.session_key;
                            wxmemberLogin(req,res,wxmemberRet);
                        } else {
                            res.send(wxmemberRet);
                        }
                    } else {
                        wxmemberRet.session_key = ret.session_key;
                        wxmemberLogin(req,res,wxmemberRet);
                    }
                } else {
                    res.send(ret);
                }
            })
        } else {
            res.send({ errorMsg: '请传入code' });
        }
    })

    //会员认证
    app.post('/v1/auth',async function (req, res) {
        if (req.body.userName && req.body.passWord) {
            let ret = await models.user.findSync({
                phone:req.body.userName,
                passWord:req.body.passWord,
                status:1
            })
            if(!ret.id){//使用手机号登录
                ret = await models.user.findSync({
                    userName:req.body.userName
                })
                if(ret.id){
                    if(ret.status != 1){
                        res.send({errorMsg:'账号未启用，请联系管理员处理'})
                        return false
                    }else if(ret.passWord != req.body.passWord){
                        res.send({errorMsg:'密码错误'})
                        return false
                    }
                }else{
                    res.send(ret)
                    return false
                }
            }
            if(!ret.id){
                //没找到对应用户
                res.send(ret);
            }else{
                let memberInfo = {
                    id:req.session.id,
                    phone:ret.phone,
                    userId:ret.id,
                    memberId:req.session.memberId,
                    name:ret.name,
                    unitId:ret.unitId
                }
                ret = await models.member.updateSync({ id:memberInfo.memberId }, memberInfo)
                wxmemberLogin(req,res, await models.member.findSync({id:memberInfo.memberId}))
                //res.send(ret.errorMsg ? ret : memberInfo)
            }
        } else {
            res.send({ errorMsg: '参数错误' })
        }
    })
    //获取小程序码 返回base64
    app.get('/v2/facility/WeChatMiniAppQrCode', function (req, res) {
        let scene = req.query.scene || $.snowflake()
        tencent.wxacode.getUnlimited({ page: 'pages/facility/qrcode/qrcode', scene }, function (ret) {
            
            if (ret.errorMsg) {
                res.send(ret);
            } else {
                fs.writeFileSync('./qrcode/' + scene + '.jpg', new Buffer.from(ret, 'binary'));
                res.sendFile(__dirname.replace('/router','') + '/qrcode/' + scene + '.jpg');
            }
        })
    })
    //获取企业微信 access_token
    app.post('/v1/company/accessToken', function (req, res) {
        request({
            url: 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwbd27fd88bd2128c0&corpsecret=SECRET',
            method: 'POST',

        }, function (err, response, ret) {
            ret = _this.formatRet(ret);
            if (ret.errtoken) {
                _this.subscribeMessage.send(args, next);
            } else {
                next(ret);
            }
        })
    })
    //记录今日微信步数
    app.post('/v1/weRunData',async (req,res) => {
        let session = req.session
        let ret = tencent.auth.decryptData(req.body.encryptedData, req.body.iv, session.session_key)
        let stepInfo = ret.stepInfoList[ret.stepInfoList.length - 1]
        let dayRunData = await models.weRunData.findSync({ userId:session.userId,timestamp:stepInfo.timestamp })
        // if(stepInfo.step == 0){
        //     let weRunData = await models.weRunData.findSync({day:$.date().Format('yyyy-MM-dd')})
        //     if(weRunData.step && weRunData.step > 100) stepInfo.step = weRunData.step - parseInt(Math.random() * 100)
            
        // }
        if(dayRunData.nodata){//不存在，插入数据库
            await models.weRunData.insertSync({
                userId:session.userId,
                day:$.date(stepInfo.timestamp * 1000).Format('yyyy-MM-dd'), 
                ...stepInfo
            })
        }else{
            await models.weRunData.updateSync({ id:dayRunData.id }, stepInfo)
        }
        res.send({})
    })
    //印刷体识别
    app.post('/v1/wxocr', async (req,res) => {
        tencent.ai.printedTextOCR(req.body.img_url,ret => {
            res.send(ret)
        })
    })
}